<?php
class httpupload{
	private $max;
	private $directory;
	private $limit=array();
	private $level=false;
	private $errors;
	public function httpupload($params=array()){
		$this->ini($params);
	}
	public function ini($vars=array(),$val=''){
		if($val!=''&&is_string($vars)){
			$vars=array($vars=>$val);
		}else if(is_object($vars)){
			$vars=get_object_vars($vars);
		}
		foreach($vars as $key=>$var){
			$this->$key=is_array($this->$key)?array_merge($this->$key,$var):$var;
		}
	}
	public function attr($field,$index){
		if(preg_match('/(.*)\[(.*)\]/',$field,$match)){
			$field=$match[1];$match[2]=is_numeric($match[2])?intval($match[2]):$match[2];
			$index=$_FILES[$field][$index==='suffix'?'name':$index][$match[2]];
		}else{
			$index=$_FILES[$field][$index==='suffix'?'name':$index];
		}
		return $index==='suffix'?strtolower(strrchr($index,'.')):$index;
	}
	public function save($field,$overwrite,$mode=0777){
		return $this->make($this->attr($field,'name'),$field,$overwrite,$mode);
	}
	public function saveAs($name,$field,$overwrite,$mode=0777){
		return $this->make($name,$field,$overwrite,$mode);
	}
	private function create(){
		$this->directory=rtrim($this->directory.'/').'/';
		if(is_dir($this->directory)){
			$this->directory.=date('Y-m').'/';
			if(!is_dir($this->directory)){
				if(!mkdir($this->directory,0740)){
					$this->errors='mkdir is error!';
					return false;
				}
			}
			$this->directory.=date('d').'/';
			if(!is_dir($this->directory)){
				if(!mkdir($this->directory,0740)){
					$this->errors='mkdir is error!';
					return false;
				}
			}
			return true;
		}else{
			return false;
		}
	}
	private function make($name,$field,$overwrite,$mode){
		if($this->attr($field,'error')===UPLOAD_ERR_OK){
			if($this->level){if(!$this->create()){return false;}}
			if($this->verify($field)){
				$source=$this->attr($field,'tmp_name');
				$target=$this->directory.$name;
				if(file_exists($target)){if($overwrite){@unlink($target);}}
				@copy($source,$target);
				@chmod($target,$mode);
				return $target;
			}else{
				return false;
			}
		}else{
			$this->errors='UPLOAD_ERROR:'.$this->attr($field,'error');
			return false;
		}
	}
	private function verify($field){
		if(!is_dir($this->directory)){
			$this->errors='upload_no_filepath';
			return false;
		}
		if(!empty($this->limit)){
			if(!in_array($this->attr($field,'suffix'),$this->limit)){
				$this->errors='upload_invalid_filetype';
				return false;
			}
		}
		$size=$this->attr($field,'size');
		if(($size>$this->max)||$size==0){
			$this->errors='File size error.';
			return false;
		}
		return true;
	}
	public function errors(){
		return $this->errors;
	}
}
?>